//前端页面展示
package com.wzy.wzyblog.web;

import com.wzy.wzyblog.service.BlogService;
import com.wzy.wzyblog.service.TagService;
import com.wzy.wzyblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;


import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

//    博客内容
    @GetMapping("/")
    public String index(@PageableDefault(size = 8, sort = {"updateTime"}, direction =
            Sort.Direction.DESC) Pageable pageable,
                        Model model) {
//        查询  blog/分类/标签   的对象进行分页
        model.addAttribute("page",blogService.listBlog(pageable));
//                                         type/tag/推荐blog 分类列表显示大小
        model.addAttribute("types", typeService.listTypeTop(6));
        model.addAttribute("tags", tagService.listTagTop(10));
        model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(8));
        return "index";
    }

//      搜索栏页面
    @PostMapping("/search")
    public String search(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model) {
//                                                                         模糊查询要自己加上%
        model.addAttribute("page", blogService.listBlog("%"+query+"%", pageable));
//        把查询的字符串返回到页面上去
        model.addAttribute("query", query);
        return "search";
    }

//     点击首页博客简介进入详情页面
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {
        model.addAttribute("blog", blogService.getAndConvert(id));
        return "blog";
    }


//    返回脚标更新内容
    @GetMapping("/footer/newblog")
    public String newblogs(Model model) {
//        脚表获取最新三个推荐博客
        model.addAttribute("newblogs", blogService.listRecommendBlogTop(3));
        return "_fragments :: newblogList";
    }

}
